﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace YasharEl.Infrastructure.ObjectFactory.ServiceModel
{
    public class DependencyContainerServiceHostFactory : ServiceHostFactory
    {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            IDependencyResolver resolver = DependencyContainer.Resolve<IDependencyResolver>();
            IDependencyRegistrar registrar = DependencyContainer.Resolve<IDependencyRegistrar>();

            object[] attributes = serviceType.GetCustomAttributes(typeof(ModuleServiceAttribute), true);
            if (attributes != null && attributes.Length == 1)
            {
                ModuleServiceAttribute moduleServiceAttribute = attributes[0] as ModuleServiceAttribute;
                if (moduleServiceAttribute != null)
                {
                    BaseDependencyContainer moduleContainer = resolver.Resolve<IDependencyContainer>().FindChildContainer(moduleServiceAttribute.ModuleName) as BaseDependencyContainer;

                    resolver = moduleContainer.DependencyResolver;
                    registrar = moduleContainer.DependencyRegistrar;
                }
            }

            return new DependencyContainerServiceHost(
                serviceType,
                resolver,
                registrar,
                baseAddresses
            );
        }
    }
}
